import {
  primaryBackgroundColor2,
  primaryColor2,
  secondaryBackgroundColor,
  secondaryBorderColor,
  primaryColor,
  primaryColor3,
  primaryBackgroundColor,
} from '../../../theme/default';
import {Text, TouchableOpacity, View, StyleSheet, Platform} from 'react-native';
import React, {useEffect, useState} from 'react';
import tw from 'twrnc';
import {TokenLogo} from '../../UI/TokenLogo';
import {useTranslation} from 'react-i18next';
import {UserToken} from '../../../db/models/userTokenModel';

import {
  calTokenValue,
  formatNumber,
  parseUnits,
  parseValue,
} from '../../../utils';
import {useTokenPriceProvider} from '../../../hooks/useTokenPriceProvider';
import {useSolanaTransaction} from '../../../hooks/useSolana/useSolanaTransaction';
import {Transaction} from '@solana/web3.js';
import {useAccountProvider} from '../../../hooks/useAccountProvider';
import {useSolanaClientProvider} from '../../../hooks/useSolana/useSolanaClientProvider';
import Toast from 'react-native-toast-message';
import LoadingModal from '../../UI/Common/LoadingModal';
import {transfer} from './demoSend/1_transfer';
type TokenItemProp = {
  userToken: UserToken;
};

const Confirm = ({route, navigation}: any) => {
  const {toAddress, amount, token} = route.params;

  const {t} = useTranslation();
  const {tokenPrices} = useTokenPriceProvider();
  const {userInfo} = useAccountProvider();
  const {solanaClient} = useSolanaClientProvider();

  const {createTransferSOLTx, createTransferSPLTx, signTx, sendRawTx} =
    useSolanaTransaction();

  const [rawTx, setRawTx] = useState<Transaction>();
  const [rawFee, setRawFee] = useState<string>('');
  const [feeValue, setFeeValue] = useState<string>('');
  const [loading, setLoading] = useState<boolean>();
  const [confirming, setConfirming] = useState<boolean>(false);

  const handleTokenValue = () => {
    const tokenPrice = tokenPrices.find(
      item => item.symbol.toLowerCase() == token.symbol.toLowerCase(),
    );
    let price = '0';
    if (tokenPrice) {
      price = tokenPrice.price;
    }
    return calTokenValue(amount, price, 6);
  };

  useEffect(() => {
    const handleFeeValue = async () => {
      if (rawFee == '') {
        setFeeValue('SGD 0');
      } else {
        const solananPrice = tokenPrices.find(
          item => item.symbol.toLowerCase() == 'sol',
        );
        if (solananPrice != undefined) {
          const feeValue = calTokenValue(
            parseValue(rawFee, 9),
            solananPrice.price,
          );
          setFeeValue(feeValue);
        } else {
          setFeeValue('SGD 0');
        }
      }
    };
    handleFeeValue();
  }, [rawFee]);

  useEffect(() => {
    const createTx = async () => {
      console.log('create tx....');
      let tx;
      if (token.type == 'native') {
        tx = await createTransferSOLTx(
          userInfo!.solanaAddress,
          toAddress,
          Number(amount),
        );
      } else {
        const amountUnits = BigInt(parseUnits(amount, token.decimals));
        tx = await createTransferSPLTx(
          userInfo!.solanaAddress,
          toAddress,
          token.address,
          amountUnits,
          token.decimals,
        );
      }
      console.log('tx', tx);
      setRawTx(tx);
      const fee = await tx.getEstimatedFee(solanaClient!);
      setRawFee(fee ? fee + '' : '');
    };
    createTx();
  }, [toAddress, amount, token]);
  console.log('userInfo!userInfo', userInfo);



  
  const Newmethde = async () => {
    if (userInfo.userType == 'commmon') {
      handelConfirm();
    } else {
      transfer(toAddress, amount);
    }
  };
  const handelConfirm = async () => {
    if (rawTx !== undefined) {
      setConfirming(true);
      try {
        const signedTx = await signTx(rawTx);
        await sendRawTx(signedTx);
        Toast.show({
          type: 'info',
          text1: t('send'),
          text2: t('txBroadcast'),
          position: Platform.OS === 'android' ? 'top' : 'bottom',
        });
        navigation.pop();
      } catch (error: any) {
        Toast.show({
          type: 'error',
          text1: t('send'),
          text2: error.toString(),
          position: Platform.OS === 'android' ? 'top' : 'bottom',
        });
      }
      setConfirming(false);
    }
  };

  return (
    <View
      style={tw.style(
        `w-full min-h-full bg-[${primaryBackgroundColor2}] p-[16px]`,
      )}>
      <View
        style={tw.style(
          'flex flex-col items-center justify-center w-full mb-[30px] gap-2 p-[16px]',
        )}>
        <TokenLogo
          tokenName={token.name}
          logoUri={token.logo}
          size={50}
          borderRadius={50}
          backgroundColor="blue"
          textFontSize={12}></TokenLogo>
        <Text style={tw.style(`text-[16px] text-[${primaryColor2}]`)}>
          {token.symbol}
        </Text>
      </View>
      <View
        style={tw.style(
          `border border border-[${secondaryBorderColor}] py-[30px] px-[20px] rounded-xl bg-[${secondaryBackgroundColor}]`,
        )}>
        <View style={tw.style(`flex flex-col gap-1`)}>
          <Text style={tw.style(`text-[${primaryColor2}] text-[12px]`)}>
            {t('amount')}
          </Text>
          <Text
            style={tw.style(`text-[${primaryColor2}] text-[16px] font-bold`)}>
            {amount} {token.symbol}
          </Text>
          <Text style={tw.style(`text-[${primaryColor2}] text-[12px]`)}>
            ≈ {handleTokenValue()}
          </Text>
        </View>
        <View style={styles.horizontalLine} />
        <View style={tw.style(`flex flex-col gap-1`)}>
          <Text style={tw.style(`text-[${primaryColor3}] text-[12px]`)}>
            {t('fees')}
          </Text>
          <Text
            style={tw.style(`text-[${primaryColor2}] text-[16px] font-bold`)}>
            {rawFee == '--'
              ? rawFee
              : `${
                  rawFee == ''
                    ? '--'
                    : formatNumber(parseValue(rawFee, 9), 2, 6)
                } SOL`}
          </Text>
          <Text style={tw.style(`text-[${primaryColor3}] text-[12px]`)}>
            ≈ {feeValue}
          </Text>
        </View>
        <View style={styles.horizontalLine} />
        <View style={tw.style(`flex flex-col gap-1`)}>
          <Text style={tw.style(`text-[${primaryColor2}] text-[12px]`)}>
            {t('to')}
          </Text>
          <Text
            style={tw.style(`text-[${primaryColor2}] text-[14px] font-bold`)}>
            {toAddress}
          </Text>
        </View>
      </View>
      <View
        style={{
          width: '100%',
          justifyContent: 'center',
          alignItems: 'center',
          marginTop: 64,
        }}>
        <TouchableOpacity style={styles.button} onPress={() => Newmethde()}>
          <Text
            style={tw.style(
              `text-[${primaryColor2}] text-center leading-10 font-bold`,
            )}>
            {t('confirm')}
          </Text>
        </TouchableOpacity>
      </View>

      <LoadingModal
        borderColor={primaryColor}
        visible={confirming}></LoadingModal>
    </View>
  );
};

const styles = StyleSheet.create({
  button: {
    width: '95%',
    height: 42,
    borderColor: primaryColor,
    backgroundColor: secondaryBackgroundColor,
    borderWidth: 1,

    borderRadius: 16,
  },
  horizontalLine: {
    borderBottomColor: '#4e4d4d',
    borderBottomWidth: 1,
    width: '100%',
    marginVertical: 10,
  },
});
export default Confirm;
